package middleware

import (
	"github.com/gin-gonic/gin"
	"go-caipu/pkg/api/helper"
	"go-caipu/pkg/api/jwt"
	"go-caipu/pkg/constant"
	"go-caipu/pkg/services/admin/sysuser"
	"net/http"

	"go-caipu/pkg/infra/log"
)

// AuthCheckRole 验证角色权限
func AuthCheckRole(user sysuser.Service, j *jwt.JWT, logger log.Logger) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//验证jwt
		jwtUser, err := tokenCheck(ctx, j, logger)
		if err != nil {
			helper.ErrorWithDetail(ctx, http.StatusUnauthorized, constant.ErrNoAuthority, err)
			ctx.Abort()
			return
		}
		//验证用户权限
		result, err := user.AuthCheckRole(ctx.Request.Context(), jwtUser, ctx.Request.Method, ctx.Request.URL.Path)
		if err != nil {
			helper.ErrorWithDetail(ctx, http.StatusUnauthorized, constant.ErrNoAuthority, err)
			ctx.Abort()
			return
		}
		if !result {
			helper.ErrorWithDetail(ctx, constant.CodeErrUnauthorized, constant.ErrNoAuthority, constant.ErrAuth)
			ctx.Abort()
			return
		}

		ctx.Next()
	}
}
